package cn.kimming.wms.util;

import java.io.File;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;

public class FileUploadUtils {
	private FileUploadUtils() {}
	
	public static final String suffix = "_small";
	
	public static String upload(File file, String fileName) {
		String uuid = UUID.randomUUID().toString();
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		String targetName = uuid + fileType;
		String smallTargetName = uuid + suffix + fileType;
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		File targetFile = new File(path, targetName);
		try {
			org.apache.commons.io.FileUtils.copyFile(file, targetFile);
			//生成缩略图
			Thumbnails.of(targetFile).scale(0.15).toFile(new File(path, smallTargetName));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "upload/" + targetName;
	}
	
	public static void delete(String imagePath) {
		String path = ServletActionContext.getServletContext().getRealPath("/");
		File file = new File(path + imagePath);
		if (file.exists()) {
			file.delete();
		}
		int index = imagePath.lastIndexOf(".");
		String smallPath = imagePath.substring(0,index) + suffix + imagePath.substring(index);
		File smallFile = new File(path + smallPath);
		if (smallFile.exists()) {
			smallFile.delete();
		}
	}
}
